package io.lkt.modules.sys.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.annotation.TableField;
import com.google.common.collect.Maps;
import com.mchange.lang.IntegerUtils;
import com.tulele.vtool.model.PlatformSysInfo;
import io.lkt.common.annotation.SysLog;
import io.lkt.common.redis.RedisCacheUtil;
import io.lkt.common.util.Query;
import io.lkt.common.util.SpringContextUtil;
import io.lkt.common.utils.*;
import io.lkt.common.validator.ValidatorUtils;
import io.lkt.modules.job.utils.HttpGetPostUtils;
import io.lkt.modules.sys.dao.SysUserGzhDao;
import io.lkt.modules.sys.entity.*;
import io.lkt.modules.sys.redis.SysConfigRedis;
import io.lkt.modules.sys.service.*;

import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.*;

import io.lkt.modules.sys.shiro.WeixinService;
import io.lkt.modules.sys.utils.SysConstant;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.datacube.WxDataCubeUserCumulate;
import me.chanjar.weixin.mp.bean.datacube.WxDataCubeUserSummary;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@CrossOrigin
@RestController
@RequestMapping({"/sys/buserinfo"})
public class BUserInfoController extends AbstractController {
    /**
     * 用户关注的渠道来源
     */
    private final static Map<String, String> subscribeSceneMap = Maps.newHashMapWithExpectedSize(9);

    static {
        subscribeSceneMap.put("ADD_SCENE_SEARCH", "公众号搜索");
        subscribeSceneMap.put("ADD_SCENE_ACCOUNT_MIGRATION", "公众号迁移");
        subscribeSceneMap.put("ADD_SCENE_PROFILE_CARD", "名片分享");
        subscribeSceneMap.put("ADD_SCENE_QR_CODE", "扫描二维码");
        subscribeSceneMap.put("ADD_SCENE_PROFILE_LINK", "图文页内名称点击");
        subscribeSceneMap.put("ADD_SCENE_PROFILE_ITEM", "图文页右上角菜单");
        subscribeSceneMap.put("ADD_SCENE_PAID", "支付后关注");
        subscribeSceneMap.put("ADD_SCENE_WECHAT_ADVERTISEMENT", "微信广告");
        subscribeSceneMap.put("ADD_SCENE_OTHERS", "其他");
    }

    @Autowired
    private BUserInfoService bUserInfoService;
    @Autowired
    SysConfigRedis sysConfigRedis;
    @Autowired
    private BUserPromotionSettleInfoService bUserPromotionSettleInfoService;
    @Autowired
    BOrderInfoService bOrderInfoService;
    @Autowired
    BUserBrandInfoService bUserBrandInfoService;
    @Autowired
    SysUserRoleService sysUserRoleService;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    RedisCacheUtil redisCacheUtil;

    @Autowired
    private SysUserGzhDao sysUserGzhDao;

    @Autowired
    BBrandInfoService bBrandInfoService;

    @Resource
    private BUserInfoNotService bUserInfoNotService;

    @Autowired
    private BArticleTypeInfoService bArticleTypeInfoService;

    @Resource
    private BUserRelateArticleTypeInfoService bUserRelateArticleTypeInfoService;

    public static final String NORMAL_VIRTUAL_VISIT_USERS = "10000013,10000015,10000047,10000062,10000076,10000240";
    public static final String TEST_VIRTUAL_VISIT_USERS = "1000001,1000002,1000003,1000004,1000007,1000009";
    @Value("${serviceUrls}")
    private String serviceUrls;

    @Autowired
    private WantedUsersService wantedUsersService;

    @Autowired
    private SysGzhService sysGzhService;

    @RequestMapping({"/list"})
    @RequiresPermissions({"sys:buserinfo:list"})
    public R list(@RequestParam Map<String, Object> params)
    {
        System.out.println(params);
        if (params.get("userIds").toString().length() > 0)
        {
            String userId = params.get("userIds").toString();

            String[] userIdArray = userId.split(",");
            params.put("userIdArray", userIdArray);
        }
        SysUserEntity curUser = getUser();
        params.put("curUserId", curUser.getUserId());

        List<SysUserGzhEntity> userGzhList = this.sysUserRoleService.queryGzhList(curUser.getUserId());
        params.put("userGzhList", userGzhList);


        String brandName = (String)params.get("brandName");
        BBrandInfoEntity bBrandInfoEntity = this.bBrandInfoService.queryByName(brandName);
        if(bBrandInfoEntity!=null){
            params.put("brandId", bBrandInfoEntity.getId());
        }

        String articleTypeName = (String)params.get("articleTypeName");
        BArticleTypeInfoEntity bArticleTypeInfoEntity = this.bArticleTypeInfoService.queryByName(articleTypeName);
        if(bArticleTypeInfoEntity!=null){
            params.put("articleTypeId", bArticleTypeInfoEntity.getId());
        }

        //20211209 hyl
        String gzhCode = (String)params.get("gzhCode");
        if(!gzhCode.equals("")) {
            PlatformSysInfo platformSysInfo = this.sysGzhService.getPlatformSysInfo(gzhCode);
            if (platformSysInfo != null) {
                params.put("gzhId", platformSysInfo.getSysGzh().getId());
            }
        }

        if (params.get("endConcernDate") != null && !params.get("endConcernDate").toString().trim().equals("")) {
            String endConcernDate = params.get("endConcernDate").toString().trim() + " 23:59:59";
            params.put("endConcernDate", endConcernDate);
        }
        Query query = new Query(params);
        List<BUserInfoEntity> brandList = this.bUserInfoService.queryList(query);

        for (BUserInfoEntity info: brandList) {
            if(info.getUserName() == null || info.getUserName().trim().equals("")){
                info.setUserName(info.getNickName());
            }
        }

        System.out.println(brandList.size());
        int total = this.bUserInfoService.userTotal(query).intValue();
        //System.out.println("总记录数：" + total);
        PageUtils pageUtil = new PageUtils(brandList, total, query.getLimit(), query.getPage());
        return R.ok().put("page", pageUtil);
    }

    @RequestMapping({"/complainList"})
    @RequiresPermissions({"sys:buserinfo:list"})
      public R complainList(@RequestParam Map<String, Object> params) {
        SysUserEntity curUser = getUser();
        List<SysUserGzhEntity> userGzhList = this.sysUserRoleService.queryGzhList(curUser.getUserId());
        params.put("userGzhList", userGzhList);
        Query query = new Query(params);
        List<BtipOffInfoEntity> tipOffInfo = this.bUserInfoService.queryComplainList(query);
        int total = this.bUserInfoService.queryComplainTotal(query).intValue();
        PageUtils pageUtil = new PageUtils(tipOffInfo, total, query.getLimit(), query.getPage());
        return R.ok().put("page", pageUtil);
    }

    @RequestMapping("/complainCount")
    public R complainCount() {
        Map<String, Object> map = new HashMap<>();
        SysUserEntity curUser = getUser();
        List<SysUserGzhEntity> userGzhList = this.sysUserRoleService.queryGzhList(curUser.getUserId());
        map.put("userGzhList", userGzhList);
        int total = this.bUserInfoService.queryTodayComplainTotal(map).intValue();
        String latestDetail = "";
        if (total > 0) {
            BtipOffInfoEntity btipOffInfoEntity = bUserInfoService.getLatestComplain(map);
            String latestTime = new SimpleDateFormat("HH:mm:ss").format(btipOffInfoEntity.getCreateTime());
            latestDetail = latestTime + "  " + btipOffInfoEntity.getNickName();
        }
        return R.ok().put("latestCount", total).put("latestDetail", latestDetail);
    }

    @RequestMapping({"/queryUserVitalByGzh"})
    @RequiresPermissions({"sys:buserinfo:list"})
    public R queryUserVitalByGzh(@RequestBody Map<String, Object> params) throws WxErrorException {
        List<BUserVitalEntity> userVitalEntities = null;
        BUserVitalEntity userVitalEntity = null;

        if (!params.get("gzhCode").toString().equals("")) {
            String gzhCode = params.get("gzhCode").toString();
            SysGzhEntity sysGzh = sysUserGzhDao.getGzhByCode(gzhCode);
            WxMpServiceImpl wxMpService = WeixinService.getWeixinService(sysGzh);
            String toDay = DateUtil.getFormatDate("yyyy-MM-dd", new Date());

            userVitalEntities = this.bUserInfoService.queryUserVitalByGzh(params);
            if ((userVitalEntities != null) && (userVitalEntities.size() > 0)) {
                userVitalEntity = (BUserVitalEntity) userVitalEntities.get(0);

                //今天触发关注数(对应手机公众号管理端)
                userVitalEntity.setJtgzCount(bUserInfoService.getSubscribeCountByAppId(sysGzh.getAppId()));

                //今天关注用户数
                userVitalEntity.setGzCount(bUserInfoService.getSubUserCountByAppId(sysGzh.getGzhCode()));

                //今天触发取关数(对应手机公众号管理端)
                userVitalEntity.setJtqgCount(bUserInfoService.getUnSubscribeCountByAppId(sysGzh.getAppId()));

                //今天取关用户数
                userVitalEntity.setQgCount(bUserInfoService.getUnSubUserCountByAppId(sysGzh.getGzhCode()));

                Integer gzhxzgzCount=0;
                Integer cancelUser=0;

                Calendar calendar = Calendar.getInstance();
                calendar.setTime(new Date());
                calendar.add(Calendar.DAY_OF_MONTH, -1);
                Date newTime1 = calendar.getTime();

                try {
                    List<WxDataCubeUserSummary> wxDataCubeUserSummaries = wxMpService.getDataCubeService().getUserSummary(newTime1, newTime1);
                    List<WxDataCubeUserCumulate> wxDataCubeUserCumulates = wxMpService.getDataCubeService().getUserCumulate(newTime1, newTime1);

                    for (WxDataCubeUserSummary wdcus : wxDataCubeUserSummaries) {

                        if (wdcus.getUserSource().equals(0)) {
                            userVitalEntity.setGzhS0Count(wdcus.getNewUser());
                        } else if (wdcus.getUserSource().equals(1)) {
                            userVitalEntity.setGzhS1Count(wdcus.getNewUser());
                        } else if (wdcus.getUserSource().equals(17)) {
                            userVitalEntity.setGzhS17Count(wdcus.getNewUser());
                        } else if (wdcus.getUserSource().equals(30)) {
                            userVitalEntity.setGzhS30Count(wdcus.getNewUser());
                        }
                        gzhxzgzCount = gzhxzgzCount + wdcus.getNewUser();
                        cancelUser = cancelUser + wdcus.getCancelUser();

                    }

                    userVitalEntity.setGzhxzgzCount(gzhxzgzCount);
                    userVitalEntity.setGzhqxgzCount(cancelUser);
                    userVitalEntity.setGzhjgzCount(gzhxzgzCount - cancelUser);
                    userVitalEntity.setGzhljgzCount(wxDataCubeUserCumulates.get(0).getCumulateUser());
                }catch (Exception e){

                }

            }
        } else {
            userVitalEntity = new BUserVitalEntity();
            //今天触发关注数(对应手机公众号管理端)
            userVitalEntity.setJtgzCount(0);

            //今天关注用户数
            userVitalEntity.setGzCount(0);

            //今天触发取关数(对应手机公众号管理端)
            userVitalEntity.setJtqgCount(0);

            //今天取关用户数
            userVitalEntity.setQgCount(0);
        }
        return R.ok().put("vital", userVitalEntity);
    }

    @RequestMapping({"/queryUserVitalByGzhMainPage"})
    @RequiresPermissions({"sys:buserinfo:list"})
    public R queryUserVitalByGzhMainPage(@RequestBody Map<String, Object> params) throws WxErrorException {
        List<BUserVitalEntity> userVitalEntities = null;
        BUserVitalEntity userVitalEntity = new BUserVitalEntity();

        if (!params.get("gzhCode").toString().equals("")) {
            String gzhCode = params.get("gzhCode").toString();

            String startDate = DateUtil.getFormatDate("yyyy-MM-dd", new Date());
            String endDate = DateUtil.getFormatDate("yyyy-MM-dd", new Date()) + " 23:59:59";

            if(params.get("pDate")!=null) {
                startDate = params.get("pDate").toString();
                endDate = params.get("pDate").toString() + " 23:59:59";
            }

            SysGzhEntity sysGzh = sysUserGzhDao.getGzhByCode(gzhCode);

            //触发关注数(对应手机公众号管理端)
            userVitalEntity.setJtgzCount(bUserInfoService.getSubscribeCountByDate(sysGzh.getAppId(), startDate, endDate));

            //触发取关数(对应手机公众号管理端)
            userVitalEntity.setJtqgCount(bUserInfoService.getUnSubscribeCountByDate(sysGzh.getAppId(), startDate, endDate));

        } else {

            //触发关注数(对应手机公众号管理端)
            userVitalEntity.setJtgzCount(0);

            //触发取关数(对应手机公众号管理端)
            userVitalEntity.setJtqgCount(0);
        }
        return R.ok().put("vital", userVitalEntity);
    }

    @RequestMapping({"/queryUserVital"})
    @RequiresPermissions({"sys:buserinfo:list"})
    public R queryUserVital(@RequestParam Map<String, Object> params)
    {
        SysUserEntity curUser = getUser();
        params.put("curUserId", curUser.getUserId());

        List<SysUserGzhEntity> userGzhList = this.sysUserRoleService.queryGzhList(curUser.getUserId());
        params.put("userGzhList", userGzhList);

        Query query = new Query(params);
        List<BUserVitalEntity> brandList = this.bUserInfoService.queryUserVital(query);
        System.out.println(brandList.size());
        int total = this.bUserInfoService.queryUserVitelTotal(query).intValue();
        PageUtils pageUtil = new PageUtils(brandList, total, query.getLimit(), query.getPage());
        return R.ok().put("page", pageUtil);
    }

    @RequestMapping({"/updateCensus"})
    @RequiresPermissions({"sys:buserinfo:list"})
    public R updateCensus()
    {
        int i= this.bUserInfoService.updateCensus();
        return R.ok();
    }



    @RequestMapping({"/export"})
    public R export(@RequestParam Map<String, Object> params)
            throws Exception
    {
        params.clear();
        params.put("limit", Integer.valueOf(110));
        params.put("page", Integer.valueOf(1));
        params.put("sidx", "refererTotal");
        Query query = new Query(params);
        List<BUserInfoEntity> brandList = this.bUserInfoService.queryList(query);
        int total = this.bUserInfoService.userTotal(query).intValue();
        PageUtils pageUtil = new PageUtils(brandList, total, query.getLimit(), query.getPage());
        return R.ok().put("page", pageUtil);
    }

    @RequestMapping({"/info/{userId}"})
    @RequiresPermissions({"sys:buserinfo:info"})
    public R info(@PathVariable("userId") Integer userId) throws WxErrorException {
        BUserInfoEntity bUserInfo = (BUserInfoEntity)this.bUserInfoService.getById(userId);
        if (bUserInfo == null) {
            return R.error("用户不存在");
        }
        String vipTime = this.bUserInfoService.vipTime(bUserInfo.getUserId());
        if (bUserInfo.getReferer() != null)
        {
            BUserInfoEntity referer = (BUserInfoEntity)this.bUserInfoService.getById(bUserInfo.getReferer());
            if (referer != null) {
                bUserInfo.setRefererPeople(referer.getNickName());
            }
        }
        bUserInfo.setVipTime(vipTime);

        String brandNames = this.bUserInfoService.getBrandNameByUserId(bUserInfo.getUserId());
        bUserInfo.setBrandName(brandNames);

        String articleTypeId = this.bUserRelateArticleTypeInfoService.getArticleTypeByUserId(bUserInfo.getUserId());
        if(articleTypeId != null && !articleTypeId.trim().equals("")) {
            String[] articleTypeIds = articleTypeId.split(",");
            String typeNames = "";
            for (String articleTypeNameInfo : articleTypeIds) {
                String typeName= this.bArticleTypeInfoService.queryById(Integer.parseInt(articleTypeNameInfo));
                typeNames = typeNames+","+typeName;
            }
            typeNames = typeNames.substring(1);

            bUserInfo.setArticleTypeName(typeNames);
        }

        //SysGzhEntity sysGzh = sysUserGzhDao.getGzhByCode(bUserInfo.getGzhCode());
        //WxMpServiceImpl wxMpService = WeixinService.getWeixinService(sysGzh);

//        WxMpUser wxMpUser = wxMpService.getUserService().userInfo(bUserInfo.getOpenId());


        return R.ok().put("bUserInfo", bUserInfo);
    }

    @SysLog("新增用户")
    @RequestMapping({"/save"})
    @RequiresPermissions({"sys:buserinfo:save"})
    public R save(@RequestBody BUserInfoEntity bUserInfo)
    {
        double money = 0.0D;
        if (bUserInfo.getVipRank() != null)
        {
            if (bUserInfo.getVipRank().intValue() == 1) {
                money = 298.0D;
            } else if (bUserInfo.getVipRank().intValue() == 2) {
                money = 398.0D;
            } else if (bUserInfo.getVipRank().intValue() == 3) {
                money = 598.0D;
            }
            bUserInfo.setVipStatus(Integer.valueOf(1));
        }
        bUserInfo.setCreateTime(new Date());
        bUserInfo.setConcernStatus(Integer.valueOf(1));
        this.bUserInfoService.save(bUserInfo);
        Integer userId = bUserInfo.getUserId();
        if (money != 0.0D)
        {
            BOrderInfoEntity bOrderInfoEntity = new BOrderInfoEntity();
            bOrderInfoEntity.setUserId(userId);
            bOrderInfoEntity.setTotalAmount(Double.valueOf(money));
            this.bOrderInfoService.addOrder(bOrderInfoEntity);
        }
        if (bUserInfo.getReferer() == null) {
            return R.ok();
        }
        BUserPromotionSettleInfoEntity settleInfoEntity = this.bUserPromotionSettleInfoService.queryByUser(bUserInfo.getReferer());
        if (settleInfoEntity != null)
        {
            settleInfoEntity.setCumulativeIncome(Double.valueOf(settleInfoEntity.getCumulativeIncome().doubleValue() + money * (settleInfoEntity.getFirstLevelProportion().doubleValue() / 100.0D)));
            settleInfoEntity.setFirstLevelCumulativeIncome(Double.valueOf(settleInfoEntity.getFirstLevelCumulativeIncome().doubleValue() + money * (settleInfoEntity.getFirstLevelProportion().doubleValue() / 100.0D)));
            settleInfoEntity.setModifyTime(new Date());
            this.bUserPromotionSettleInfoService.updateById(settleInfoEntity);
        }
        System.out.println(settleInfoEntity.getCumulativeIncome());
        return R.ok();
    }

    @SysLog("查询备注")
    @RequestMapping({"/infonot"})
    @RequiresPermissions({"sys:buserinfo:info"})
    public R infonot(@RequestBody Integer buserinfo_id){
        List<BUserInfoNot> listnot = this.bUserInfoNotService.selectBUserInfoNotList(buserinfo_id);
        if (listnot == null) {
            return R.error("暂时无备注");
        }
        return R.ok().put("listnot", listnot);
    }

    @SysLog("新增备注")
    @RequestMapping({"/save2"})
    @RequiresPermissions({"sys:buserinfo:save"})
    public R save(@RequestBody BUserInfoNot bUserInfoNot) {
        //获取当前登录用户
        SysUserEntity curUser = getUser();
        bUserInfoNot.setRemarksUser(curUser.getUsername());

        bUserInfoNot.setRemarksTime(new Date());

        this.bUserInfoNotService.insert(bUserInfoNot);
        return R.ok();
    }

    @SysLog("修改用户")
    @RequestMapping({"/update"})
    @RequiresPermissions({"sys:buserinfo:update"})
    public R update(@RequestBody BUserInfoEntity bUserInfo)
            throws Exception
    {
        int day = 0;

        ValidatorUtils.validateEntity(bUserInfo, new Class[0]);
        this.bUserInfoService.updateById(bUserInfo);
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet get = null;
        if ((bUserInfo.getGiveType().equals(Integer.valueOf(1))) || (bUserInfo.getGiveType().equals(Integer.valueOf(2))))
        {
            SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");
            if (bUserInfo.getGiveVipDate() != null)
            {
                long from1 = new Date().getTime();
                if ((bUserInfo.getVipTime() != null) && (bUserInfo.getVipTime().trim().length() > 0)) {
                    from1 = simpleFormat.parse(bUserInfo.getVipTime()).getTime();
                }
                long to1 = simpleFormat.parse(bUserInfo.getGiveVipDate() + " 23:59").getTime();
                day = (int)((to1 - from1) / 86400000L);
            }
            if (bUserInfo.getVipRank().intValue() != 4) {
                day = bUserInfo.getVipRank().intValue();
            }
            if (day > 0)
            {
                bUserInfo.setVipStatus(Integer.valueOf(1));
                this.bUserInfoService.updateById(bUserInfo);
                Map<String, Object> map = new HashMap();
                map.put("userId", bUserInfo.getUserId());
                map.put("createTime", new Date());
                map.put("dayToal", Integer.valueOf(day));
                this.bUserInfoService.addVipLog(map);

//                String virtualUserInfo = "10000013,10000015,10000047,10000062,10000076,10000240";
//                String profile = SpringContextUtil.getActiveProfile();
//                if ("10000013,10000015,10000047,10000062,10000076,10000240".equals(profile)) {
//                    virtualUserInfo = "10000013,10000015,10000047,10000062,10000076,10000240";
//                }
//                List<String> virtualUsers = Arrays.asList(virtualUserInfo.split(","));
//                this.bUserInfoService.deleteVirtualVisitUsers(virtualUsers, bUserInfo.getUserId());

                HttpGetPostUtils.delCache(this.serviceUrls, "LookArticleInfoMapper");
                // 2021-09-29
                // 如果用户为赠送vip（[vip赠送类型]为[按时长赠送]，且[设置为高级会员] 是[一百年]），视为永久会员。用户人脉广场的每日加好友次数更新为50次
                if (bUserInfo.getGiveType().equals(Integer.valueOf(2)) && bUserInfo.getVipRank().equals(Integer.valueOf(36500))) {
                    map.put("dayFriendCount", 50);
                } else {
                    map.put("dayFriendCount", 30);
                }
                if (this.bUserInfoService.vipValidTotal(bUserInfo.getUserId()).intValue() > 0) {
                    this.bUserInfoService.setVipValid(map);
                } else {
                    this.bUserInfoService.addVipValid(map);
                }
                HttpGetPostUtils.delCache(this.serviceUrls, "UserVipValidInfoMapper");
            }
        }
        this.bUserBrandInfoService.storeUserSubBrand(bUserInfo.getUserId(), bUserInfo.getBrandName());

        String articleTypeStrName = bUserInfo.getArticleTypeName();
        if(articleTypeStrName != null && !articleTypeStrName.trim().equals("")) {
            String[] articleTypeStrNames = articleTypeStrName.split(",");
            String typeIds = "";
            for (String articleTypeNameInfo : articleTypeStrNames) {
                Integer typeId= this.bArticleTypeInfoService.queryByStr(articleTypeNameInfo);
                typeIds = typeIds+","+typeId.toString();
            }
            typeIds = typeIds.substring(1);

            bUserInfo.setArticleTypeId(typeIds);

            this.bUserRelateArticleTypeInfoService.updateTypeStrId(bUserInfo.getUserId(), bUserInfo.getArticleTypeId());
        }

        HttpGetPostUtils.delCache(this.serviceUrls, "UserBrandInfoMapper");

        return R.ok();
    }

    /**
     * 赠送一年 VIP (只针对公众号[共建获客平台])
     * @return
     * @throws Exception
     */
    @RequestMapping({"/giveAYearVip/{userId}"})
    @RequiresPermissions({"sys:buserinfo:givevip"})
    public R giveAYearVip(@PathVariable("userId") Integer userId) throws Exception {
        // 1、更新用户 VIP 状态
        BUserInfoEntity bUserInfo = new BUserInfoEntity();
        bUserInfo.setUserId(userId);
        bUserInfo.setVipStatus(Integer.valueOf(1));
        bUserInfo.setModifyTime(new Date());
        this.bUserInfoService.updateById(bUserInfo);

        // 2、添加用户 vip 日志
        Map<String, Object> map = new HashMap();
        map.put("userId", bUserInfo.getUserId());
        map.put("createTime", new Date());
        map.put("dayToal", Integer.valueOf(365));
        this.bUserInfoService.addVipLog(map);

        // 刷新缓存
        // HttpGetPostUtils.delCache(this.serviceUrls, "LookArticleInfoMapper");

        // 3、用户 VIP 详情
        map.put("dayFriendCount", 30);
        if (this.bUserInfoService.vipValidTotal(bUserInfo.getUserId()).intValue() > 0) {
            this.bUserInfoService.setVipValid(map);
        } else {
            this.bUserInfoService.addVipValid(map);
        }

        // 4、用户备注
        //获取当前登录用户
        BUserInfoNot bUserInfoNot = new BUserInfoNot();
        SysUserEntity curUser = getUser();
        bUserInfoNot.setRemarksUser(curUser.getUsername());
        bUserInfoNot.setRemarksTime(new Date());
        bUserInfoNot.setRemarksContent("共建集团，送会员一年");
        bUserInfoNot.setBuserinfoId(userId);

        this.bUserInfoNotService.insert(bUserInfoNot);

        HttpGetPostUtils.delCache(this.serviceUrls, "UserVipValidInfoMapper");
        HttpGetPostUtils.delCache(this.serviceUrls, "UserInfoMapper");

        return R.ok();
    }

    @SysLog("创建优惠券链接")
    @RequestMapping({"/createCouponLink"})
    @RequiresPermissions({"sys:buserinfo:update"})
    public R createCouponLink(@RequestBody BUserInfoEntity pUserInfo)
            throws Exception
    {
        int day = 0;
        ValidatorUtils.validateEntity(pUserInfo, new Class[0]);
        BUserInfoEntity bUserInfo = (BUserInfoEntity)this.bUserInfoService.getById(pUserInfo.getUserId());
        if (bUserInfo == null) {
            return R.error("用户不存在");
        }
        if ((bUserInfo != null) && (bUserInfo.getUserId().intValue() > 0))
        {
            TempCouponEntity tempCouponEntity = new TempCouponEntity();
            tempCouponEntity.setUser_id(bUserInfo.getUserId());
            tempCouponEntity.setCreate_time(new Date());
            this.redisCacheUtil.setCacheObject("ADD_COUPON_TIMELINESS:" + bUserInfo.getUserId(), JSON.toJSONString(tempCouponEntity), 600L);

            SysGzhEntity sysGzh = this.sysUserRoleService.getGzhByCode(bUserInfo.getGzhCode());
            if (sysGzh != null) {
                return R.ok().put("couponUrl", sysGzh.getRealmName() + "pages/setting/member.html?v=" + new Date().getTime());
            }
        }
        return R.ok();
    }

    @SysLog("删除用户")
    @RequestMapping({"/delete"})
    @RequiresPermissions({"sys:buserinfo:delete"})
    public R delete(@RequestBody Integer userId)
    {
        this.bUserInfoService.removeById(userId);
        String redisKey = "wxPushUser" + userId;
        this.sysConfigRedis.delete(redisKey);
        return R.ok();
    }

    @SysLog("拉黑用户")
    @RequestMapping({"/block"})
    @RequiresPermissions({"sys:buserinfo:delete"})
    public R block(@RequestBody Integer userId)
    {
        this.bUserInfoService.blockByUser(userId);

        //后台拉黑用户时记录 start
        SysUserEntity curUser = getUser();
        BUserInfoEntity userInfo = bUserInfoService.getById(userId);
        WantedUsersLogEntity wantedUsersLog = new WantedUsersLogEntity();
        wantedUsersLog.setUserId(userId);
        wantedUsersLog.setNickName(userInfo.getNickName());
        wantedUsersLog.setAvatarUrl("后台:"+curUser.getUsername()+"/"+curUser.getUserId());
        wantedUsersLog.setGzhCode(userInfo.getGzhCode());
        wantedUsersLog.setCreateTime(new Date());
        wantedUsersService.addWantedUsersLog(wantedUsersLog);
        //后台拉黑用户时记录 end

        return R.ok();
    }

    @SysLog("移出黑名单")
    @RequestMapping({"/cancelblock"})
    @RequiresPermissions({"sys:buserinfo:delete"})
    public R cancelblock(@RequestBody Integer userId)
    {
        this.bUserInfoService.cancelBlockByUser(userId);
        return R.ok();
    }

    @SysLog("处理投诉")
    @RequestMapping({"/handle"})
    @RequiresPermissions({"sys:buserinfo:delete"})
    public R handle(@RequestBody Integer id)
    {
        this.bUserInfoService.handle(id);
        return R.ok();
    }

    @ResponseBody
    @RequestMapping(value={"/referer"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
    public R referer(@RequestParam Map<String, Object> params)
    {
        if (params == null) {
            return R.error("请求失败");
        }
        Query query = new Query(params);
        System.out.println(params);
        Integer referer = Integer.valueOf(Integer.parseInt(params.get("referer").toString().trim()));
        int fufeiTotal = this.bUserInfoService.fufei(referer).intValue();
        int secondFufei = this.bUserInfoService.secondFufei(query).intValue();
        List<BUserInfoEntity> list = this.bUserInfoService.referer(query);
        List<BUserInfoEntity> secondReferer = this.bUserInfoService.secondReferer(query);
        for (BUserInfoEntity user : secondReferer)
        {
            Map<String, Object> map = new HashMap();
            map.put("referer", user.getReferer());
            Integer total = this.bUserInfoService.secondRefererTotal(map);
            user.setSecondRefererTotal(total);
        }
        int secondTotal = this.bUserInfoService.secondTotal(query).intValue();
        int total = this.bUserInfoService.refererTotal(query).intValue();
        PageUtils pageUtil = new PageUtils(list, total, query.getLimit(), query.getPage());
        PageUtils pageUtils = new PageUtils(secondReferer, secondTotal, query.getLimit(), query.getPage());
        return R.ok().put("page", pageUtil).put("fufeiTotal", Integer.valueOf(fufeiTotal)).put("pages", pageUtils).put("secondFufei", Integer.valueOf(secondFufei));
    }

    @ResponseBody
    @RequestMapping(value={"/brandUser"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
    public R brandUser(@RequestParam Map<String, Object> params)
    {
        if (params == null) {
            return R.error("请求失败");
        }
        Query query = new Query(params);
        System.out.println(query);
        List<BrandUserEntity> brandUser = this.bUserInfoService.brandUser(query);
        int brandPayUserTotal = this.bUserInfoService.brandPayUserTotal(query);
        int brandUserTotal = this.bUserInfoService.brandUserTotal(query);
        BrandUserEntity brandUserInfoHead = this.bUserInfoService.brandUserHead(query);
        brandUserInfoHead.setBrnadUserTotal(Integer.valueOf(brandUserTotal));
        brandUserInfoHead.setBrnadPayUserTotal(Integer.valueOf(brandPayUserTotal));
        PageUtils pageUtil = new PageUtils(brandUser, brandUserTotal, query.getLimit(), query.getPage());
        return R.ok().put("brandUser", pageUtil).put("brandUserInfoHead", brandUserInfoHead);
    }

    @ResponseBody
    @RequestMapping(value={"/brandPayUser"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
    public R brandPayUser(@RequestParam Map<String, Object> params)
    {
        if (params == null) {
            return R.error("请求失败");
        }
        Query query = new Query(params);
        List<BrandUserEntity> brandPayUser = this.bUserInfoService.brandPayUser(query);
        int brandPayUserTotal = this.bUserInfoService.brandPayUserTotal(query);
        int brandUserTotal = this.bUserInfoService.brandUserTotal(query);
        BrandUserEntity brandUserInfoHead = this.bUserInfoService.brandUserHead(query);
        brandUserInfoHead.setBrnadUserTotal(Integer.valueOf(brandUserTotal));
        brandUserInfoHead.setBrnadPayUserTotal(Integer.valueOf(brandPayUserTotal));
        PageUtils pageUtil = new PageUtils(brandPayUser, brandPayUserTotal, query.getLimit(), query.getPage());
        return R.ok().put("brandPayUser", pageUtil).put("brandUserInfoHead", brandUserInfoHead);
    }

    @ResponseBody
    @RequestMapping(value={"/getUserGzhList"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
    public R getUserGzhList()
    {
        SysUserEntity curUser = getUser();

        List<SysUserGzhEntity> userGzhList = this.sysUserRoleService.queryGzhList(curUser.getUserId());

        return R.ok().put("userGzhList", userGzhList);
    }

    @ResponseBody
    @RequestMapping(value={"/getAllCategory"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
    public R getAllCategory(){
        List<BBrandCategoryEntity> bBrandCategory = bBrandInfoService.getAllCategory();

        return R.ok().put("bBrandCategory", bBrandCategory);
    }

    @SysLog("更新微信昵称")
    @RequestMapping({"/updateUserName"})
//    @RequiresPermissions({"sys:buserinfo:updateUserName"})
    public R updateUserName(@RequestBody Integer userId){
        if (userId == null) {
            return R.error("请求失败");
        }
        BUserInfoEntity userInfo = bUserInfoService.getById(userId);
        if (userInfo != null && userInfo.getOpenId() != null) {
            SysGzhEntity sysGzh = sysUserGzhDao.getGzhByCode(userInfo.getGzhCode());
            try {
                WxMpServiceImpl wxMpService = WeixinService.getWeixinService(sysGzh);
                WxMpUser wxUser = wxMpService.getUserService().userInfo(userInfo.getOpenId());
                //昵称
                userInfo.setUserName(wxUser.getNickname());
                userInfo.setModifyTime(new Date());
                this.bUserInfoService.updateById(userInfo);
                return R.ok();
            } catch (WxErrorException e) {
                e.printStackTrace();
            }
        }
        return R.error("请求失败");
    }

    @SysLog("获取微信头像")
    @RequestMapping({"/getHeadImgUrl"})
//    @RequiresPermissions({"sys:buserinfo:getHeadImgUrl"})
    public R getHeadImgUrl(@RequestBody Integer userId){
        if (userId == null) {
            return R.error("请求失败");
        }
        BUserInfoEntity userInfo = bUserInfoService.getById(userId);
        if (userInfo != null && userInfo.getOpenId() != null) {
            SysGzhEntity sysGzh = sysUserGzhDao.getGzhByCode(userInfo.getGzhCode());
            try {
                WxMpServiceImpl wxMpService = WeixinService.getWeixinService(sysGzh);
                WxMpUser wxUser = wxMpService.getUserService().userInfo(userInfo.getOpenId());
                //头像
                String headImgUrl=wxUser.getHeadImgUrl();
                if(headImgUrl.contains("/132")){
                    headImgUrl=headImgUrl.replace("/132","/0");
                }

                // 用户关注的渠道来源
                String subscribeSceneTxt = "";
                String subscribeSceneCode = wxUser.getSubscribeScene();
                if (StringUtils.isNotBlank(subscribeSceneCode)) {
                    subscribeSceneTxt = Optional.ofNullable(subscribeSceneMap.get(subscribeSceneCode)).orElse("");
                }

                return R.ok().put("headImgUrl", headImgUrl).put("subscribeScene", subscribeSceneTxt);
            } catch (WxErrorException e) {
                e.printStackTrace();
            }
        }
        return R.error("请求失败");
    }

    @SysLog("加入通缉名单")
    @RequestMapping({"/addWantedUser"})
    public R addWantedUser(@RequestBody Integer userId) throws Exception {
        if (userId == null) {
            return R.error("请求失败");
        }
        System.out.println(userId);
        BUserInfoEntity userInfo = bUserInfoService.getById(userId);
        this.bUserInfoService.blockByUser(userId);
        //后台拉黑用户时记录 start
        SysUserEntity curUser = getUser();
        WantedUsersLogEntity wantedUsersLog = new WantedUsersLogEntity();
        wantedUsersLog.setUserId(userId);
        wantedUsersLog.setNickName(userInfo.getNickName());
        wantedUsersLog.setAvatarUrl("后台:"+curUser.getUsername()+"/"+curUser.getUserId());
        wantedUsersLog.setGzhCode(userInfo.getGzhCode());
        wantedUsersLog.setCreateTime(new Date());
        wantedUsersService.addWantedUsersLog(wantedUsersLog);
        //后台拉黑用户时记录 end

        boolean queryInWanted = wantedUsersService.queryInWanted(userInfo);
        if(queryInWanted){
            return R.error("已经在通缉名单");
        }

        WantedUsersEntity wantedUsersEntity = new WantedUsersEntity();

        wantedUsersEntity.setUserId(userInfo.getUserId());
        wantedUsersEntity.setNickName(userInfo.getNickName());
        wantedUsersEntity.setAvatarUrl(userInfo.getAvatarUrl());
        wantedUsersEntity.setOpenId(userInfo.getOpenId());
        wantedUsersEntity.setGzhCode(userInfo.getGzhCode());
        wantedUsersEntity.setCreateBy(getUser().getUsername());
        wantedUsersEntity.setCreateTime(new Date());

        int creatWanted = wantedUsersService.creatWanted(wantedUsersEntity);

        if(creatWanted > 0){
            return R.ok("操作成功");
        }

        return R.error("请求失败");
    }

    @SysLog("获取下级")
    @RequestMapping({"/getSubordinate"})
//    @RequiresPermissions({"sys:buserinfo:getHeadImgUrl"})
    public R getSubordinate(@RequestBody Integer userId){
        if (userId == null) {
            return R.error("请求失败");
        }

        // 下级 - 一级
        List<UserChildrenEntity> oneList = bUserInfoService.getSubordinate(userId);

//        // 下级 - 二级
//        for (UserChildrenEntity info : oneList) {
//            info.setChildren(bUserInfoService.getSubordinate(info.getValue()));
//        }

        // 自己
        UserChildrenEntity oneself = new UserChildrenEntity();
        BUserInfoEntity userInfo = bUserInfoService.getById(userId);

        oneself.setName(userInfo.getNickName());
        oneself.setValue(userInfo.getUserId());
        oneself.setSymbol(userInfo.getAvatarUrl());
        oneself.setSymbolSize(25);
        oneself.setChildren(oneList);

        List<UserChildrenEntity> oneselfList = new ArrayList<>();
        oneselfList.add(oneself);

        // 父级 - 一级
        UserChildrenEntity parent = new UserChildrenEntity();

        if(userInfo != null && userInfo.getReferer() != null) {
            BUserInfoEntity RefererUserInfo = bUserInfoService.getById(userInfo.getReferer());

            if(RefererUserInfo != null){
                parent.setName(RefererUserInfo.getNickName());
                parent.setValue(RefererUserInfo.getUserId());
                parent.setSymbol(RefererUserInfo.getAvatarUrl());
                parent.setSymbolSize(25);
                parent.setChildren(oneselfList);

                List<UserChildrenEntity> parentList = new ArrayList<>();
                parentList.add(parent);

                return R.ok().put("children", parentList);
            }

        }
        return R.ok().put("children", oneselfList);
    }

    @SysLog("获取下级(含一级和二级)")
    @RequestMapping({"/getSubUser"})
    public R getSubUser(Integer userId){
        if (userId == null) {
            return R.error("请求失败");
        }
        List<BUserInfoEntity> subUserList = bUserInfoService.getSubUser(userId);
        return R.ok().put("subUserList", subUserList);
    }

    /**
     * 获取用户的打卡记录
     * @param params
     * @return
     */
    @RequestMapping("/clockInfo")
    public R getUserClockInfo(@RequestParam Map<String, Object> params) {
        if (params.get("userId") == null) {
            return R.error("请求失败");
        }
        Query query = new Query(params);
        List<BUserPunchClockInfoEntity> list = bUserInfoService.getUserClockInfo(query);
        int total = bUserInfoService.getClockInfoTotal(query).intValue();
        PageUtils page = new PageUtils(list, total, query.getLimit(), query.getPage());
        return R.ok().put("page", page);
    }

    @GetMapping("/getSubUserCount/{userId}")
    public R getSubUserCount(@PathVariable("userId") Integer userId) {
        if (userId == null || userId <= 0) {
            return R.error("访问失败");
        }
        int subUserCount = bUserInfoService.getSubUserCount(userId);
        return R.ok().put("subUserCount", subUserCount);
    }

    @GetMapping("/getUserClockCount/{userId}")
    public R getUserClockCount(@PathVariable("userId") Integer userId) {
        if (userId == null || userId <= 0) {
            return R.error("访问失败");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("userId", userId);

        int userClockCount = bUserInfoService.getClockInfoTotal(map).intValue();
        return R.ok().put("userClockCount", userClockCount);
    }


    Integer testCount;

    @RequestMapping({"/setCount"})
    public R setCount(@RequestBody Map<String, Object> params) throws WxErrorException, InterruptedException {
        this.testCount = 1;
        System.out.println("setCount启动："+Thread.currentThread().getId()+"_"+this.hashCode());
        while (true) {
            this.testCount++;
            Thread.sleep(1000);
        }
    }

    @RequestMapping({"/getCount"})
    public R getCount(@RequestBody Map<String, Object> params) throws WxErrorException, InterruptedException {
        System.out.println("getCount启动："+Thread.currentThread().getId()+"_"+this.hashCode());
        while (true) {
            System.out.println("testCount="+this.testCount);
            Thread.sleep(1000);
        }
    }

    /**
     * 根据用 ID 获取用户的主用户 ID
     * @param userId
     * @return
     */
    @RequestMapping("/mainUser/{userId}")
    public R getMainUserId(@PathVariable("userId") Integer userId) {
        if (userId == null || userId <= 0) {
            return R.error("用户不存在");
        }
        BUserGroupOpenidEntity entity = bUserInfoService.getMainUserId(userId);
        Integer mainUserId = entity == null ? null : entity.getUserId();
        return R.ok().put("mainUserId", mainUserId);
    }

    /**
     * 根据用户 ID 获取用户在一个组中其他关注的关注号信息
     * @param params
     * @return
     */
    @RequestMapping("/userOtherFollowGzh")
    public R getUserOtherFollowGzh(@RequestParam Map<String, Object> params) {
        if (params.get("userId") == null) {
            return R.error("用户不存在");
        }

        // 1、获取用户的主用户ID
        Integer userId = Integer.parseInt(params.get("userId").toString());
        //BUserGroupOpenidEntity entity = bUserInfoService.getMainUserId(userId);

        String unionId= bUserInfoService.getUnionId(userId);

        List<BUserInfoEntity> list = new ArrayList<>(0);
        int total = 0;
        Query query = new Query(params);

        if (unionId != null && !unionId.equals("")) {
            //query.put("mainUserId", entity.getUserId());
            query.put("unionId", unionId);

            list = bUserInfoService.getUserOtherFollowGzh(query);
            total = bUserInfoService.getUserOtherFollowGzhTotal(query).intValue();
        }

        PageUtils page = new PageUtils(list, total, query.getLimit(), query.getPage());
        return R.ok().put("page", page);
    }

    @RequestMapping("/referrerInfo")
    public R getReferrerInfo(@RequestParam Map<String, Object> params) {
        if (params.get("endDate") != null && !params.get("endDate").toString().trim().equals("")) {
            String endDate = params.get("endDate").toString().trim() + " 23:59:59";
            params.put("endDate", endDate);
        }
        List<SysUserGzhEntity> userGzhList = this.sysUserRoleService.queryGzhList(getUserId());
        params.put("userGzhList", userGzhList);

        Query query = new Query(params);
        List<BUserInfoEntity> list = bUserInfoService.getReferrerInfo(query);
        int total = bUserInfoService.getReferrerInfoTotal(query).intValue();

        PageUtils page = new PageUtils(list, total, query.getLimit(), query.getPage());
        return R.ok().put("page", page);
    }

    @RequestMapping("/unsubscribe")
    public R unsubscribe(@RequestParam Map<String, Object> params) {
        List<SysUserGzhEntity> userGzhList = this.sysUserRoleService.queryGzhList(getUserId());
        params.put("userGzhList", userGzhList);

        if (params.get("brandName") != null) {
            String brandName = (String)params.get("brandName");
            BBrandInfoEntity bBrandInfoEntity = this.bBrandInfoService.queryByName(brandName);
            if(bBrandInfoEntity!=null){
                params.put("brandId", bBrandInfoEntity.getId());
            }
        }

        Query query = new Query(params);
        List<BUserInfoEntity> list = bUserInfoService.getUnsubscribeUser(query);
        int total = bUserInfoService.getUnsubscribeUserTotal(query).intValue();

        PageUtils page = new PageUtils(list, total, query.getLimit(), query.getPage());
        return R.ok().put("page", page);
    }

    // 获取关注进来、过了两了小时 没有分享的用户，显示二维码、手机。

    @RequestMapping("//noWorthUser")
    public R noWorthUser(@RequestParam Map<String, Object> params) {
        List<SysUserGzhEntity> userGzhList = this.sysUserRoleService.queryGzhList(getUserId());
        params.put("userGzhList", userGzhList);

        Query query = new Query(params);
        List<BUserInfoEntity> list = bUserInfoService.getNoWorthUser(query);
        int total = bUserInfoService.getNoWorthUserTotal(query).intValue();

        PageUtils page = new PageUtils(list, total, query.getLimit(), query.getPage());
        return R.ok().put("page", page);
    }
}
